package com.ocom.oauth.auth.wx;

import com.alibaba.fastjson.JSON;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.HttpRequest;
import com.ocom.common.utils.RequestUtil;
import com.ocom.oauth.client.HumanClientService;
import com.ocom.security.authentication.YoCiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 *  说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class WxUserDetailService {


    @Autowired
    HumanClientService humanClientService;

    @Value("${wx.appid}")
    private  String appid;

    @Value("${wx.secret}")
    private  String secret;

    //管理小程序获取用户
    public UserDetails loadByCode(String code,String from) {

        String openId = "";


        if(from.equals("gzh")){
            String appid1 = "wx8f1e72875485d9de";
            String secret1 = "2831b782d376d03de28708059ba85f1b";

            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid1 + "&secret=" + secret1 + "&code=" + code + "&grant_type=authorization_code";

            Map<String,String> map = JSON.parseObject(HttpRequest.sendGet(url), Map.class);
            log.info("登录 微信返回信息 68= {{}}", map);

            if(map.containsKey("errcode")){
                throw new InvalidGrantException(map.get("errmsg"));
            }

            openId = map.get("openid");
        } else  if ("sobyte".equals(from)) {
          log.info("sobyte小程序请求openID");
          //为了支持 sobyte 小程序的登录
          String appid1 = "wx6338d0e792231de0";
          String secret1 = "f65b420dda6126d00fb11fa0cfac0da9";
          String url=
              "https://api.weixin.qq.com/sns/jscode2session?appid="+ appid1 +"&secret="+ secret1 +"&js_code="+  code +"&grant_type=authorization_code";
          RequestUtil requestUtil=new RequestUtil();
          Map<String,String> map =requestUtil.doGetRequest(url);

          if(map.containsKey("errcode")){
            throw new InvalidGrantException(map.get("errmsg"));
          }

          openId =  map.get("openid");

        }else{
            log.info("管理小程序请求openID");
            String url="https://api.weixin.qq.com/sns/jscode2session?appid="+ appid +"&secret="+ secret +"&js_code="+  code +"&grant_type=authorization_code";
            RequestUtil requestUtil=new RequestUtil();
            Map<String,String> map =requestUtil.doGetRequest(url);

            if(map.containsKey("errcode")){
                throw new InvalidGrantException(map.get("errmsg"));
            }

            openId =  map.get("openid");
        }

//        map.put("openid","oYviH4npaE9N38FfW-bZg4bcXijY");

        //{errcode=40013, errmsg=invalid appid, rid: 61ceb753-441d1ecc-356d9165}
        //{openid=oYviH4npaE9N38FfW-bZg4bcXijY, session_key=GzzTarsUi+gkRNxDT+AfPg==}

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_WX"));

        Set<String> permissions = new HashSet<>();
        permissions.add("sys:user:admin");

        Result result = humanClientService.getWxAdminInfo(appid,openId);
        List<Long> list =new ArrayList<>();
        if(result.getCode()==200 && result.getData()!=null){
            list = JSON.parseObject(JSON.toJSONString(result.getData()),List.class);
        }

//        return new YoCiUser(map.get("openid"), list, authorities);
        return new YoCiUser(0l, 0l,0l,"0", permissions, openId , "", true, true , true,
        true,
        authorities,list);


    }

}
